﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NCC_SOP.app_codes;

namespace NCC_SOP
{
    public partial class pdfViewer : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            CommonUID names = new CommonUID();

            Session[names.userID] = Page.User.Identity.Name;

            if (!IsPostBack)
            {
                string userID = (string)Session[names.userID];
                string rptID = Request.QueryString["rptID"];

                AuditUtil audit = new AuditUtil();
                audit.auditLog_viewRpt(rptID, userID);

                webUtilities util = new webUtilities();
                string PDFName = util.getPDFURLbyRptID(rptID);
                PDFName = PDFName.Replace("/", "\\");
                if (!PDFName.Equals("NA"))
                {
                    try
                    {
                        string targetFolder = System.Web.HttpContext.Current.Server.MapPath("~/");
                        string fileName = targetFolder + PDFName;
                        byte[] ByteArray = System.IO.File.ReadAllBytes(fileName);

                        Response.Clear();
                        //Send the file to the output stream
                        Response.Buffer = true;

                        //Try and ensure the browser always opens the file and doesn’t just prompt to "open/save".
                        Response.AddHeader("Content-Length", ByteArray.Length.ToString());
                        Response.AddHeader("Content-Disposition", "inline; filename=" + PDFName);
                        Response.AddHeader("Expires", "0");
                        Response.AddHeader("Pragma", "cache");
                        Response.AddHeader("Cache-Control", "private");

                        //Set the output stream to the correct content type (PDF).
                        Response.ContentType = "application/pdf";

                        //Output the file
                        Response.BinaryWrite(ByteArray);

                        //Flushing the Response to display the serialized data
                        //to the client browser.
                        Response.Flush();
                        try { Response.End(); }
                        catch { }
                    }
                    catch {
                        this.errorMsg.Visible = true;
                        this.errorMsg.Text = "PDF file is corrupted. Pls contact administrator.";
                    }
                }
            }
        }
    }
}